<template>
  <div>
    <a-input placeholder="请输入商品名称"  v-model="inputText"
        type="text"
        @input="checkForSpace"
        @keydown.enter="addTag"/>

      <div class="tags" style="margin-top:5px;">
        <div
          v-for="(tag, index) in tags"
          :key="index"
          class="tag"
        >
          {{ tag }}
          <span class="close" @click="removeTag(index)">&times;</span>
        </div>
      </div>

  </div>
</template>

<script>
export default {
  name: "InputTag",
  props: {dic: {type: String, default: ''}},
  data() {
    return {
      inputText: '',
      tags: [],
    };
  },
  created() {

    this.tags = this.dic.split(',') || [];//关键字初始化，dic的值来自于父组件（调用它的组件叫父组件）
  },
  watch:{
      "dic":{
        immediate:true,
        handler(val){
          console.log('val',val)
          if(!val){

          }else{
            var myVar = this.dic.search(',');
            console.log('myVar',myVar)
            var data = this.dic.split(',')
            console.log('myVardata',data)
          }
        }
      },
    },
  methods: {
    addTag() {
      if (this.inputText.trim() !== '') {
        this.tags.push(this.inputText);
        this.inputText = '';
      }
    },
    removeTag(index) {
      this.tags.splice(index, 1);
    },
    checkForSpace() {
      if (this.inputText.endsWith(' ')) {
        this.addTag();
      }
    },
  },
};
</script>

<style>
.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag {
  background: #ddd;
  padding: 4px;
  border-radius: 4px;
}

.close {
  margin-left: 4px;
  cursor: pointer;
}
</style>


